import { ref, unref, computed, watch, readonly } from 'vue';

function useTimeline(props) {
	
	const point = ref();
	const ranges = ref([]);
	const status = ref(false);
	
	let prevTime = null;
	let pace = props?.pace || true;
	let rate = props?.rate || 1;
	let duration = props?.duration || Infinity;
	let loop = props?.loop || false;
	
	watch(status, (newStatus, oldStatus) => {
		props?.[newStatus ? 'onPlay' : 'onPause']?.(point.value);
	})
	
	function start(pt = null) {
		stop();
		point.value = pt != null ? pt : point.value || 0;
		status.value = true;
		record();
	}
	
	function stop() {
		status.value = false;
		prevTime = null;
	}
	
	function record() {
		if (!status.value) return;
		const nextTime = new Date();
		const nextPoint = point.value + (prevTime ? nextTime - prevTime : 0) * (pace ? 1 : -1) * rate;
		if (nextPoint >= duration) {
			props?.onEnd?.();
			point.value = duration;
			if (loop) {
				props?.onLoop?.();
				start(0);
			} else {
				stop();
			}
		} else {
			point.value = nextPoint;
			prevTime = nextTime;
		}
		requestAnimationFrame(() => record());
	}
	
	function setPace(newPace) {
		pace = newPace;
	}
	
	function getPace() {
		return pace;
	}
	
	function setRate(newRate) {
		rate = newRate;
	}
	
	function getRate() {
		return rate;
	}
	
	function setDuration(newDuration) {
		duration = newDuration;
	}
	
	function getDuration() {
		return duration;
	}
	
	function setLoop(newLoop) {
		loop = newLoop;
	}
	
	function getLoop() {
		return loop;
	}
	
	return {
		point: readonly(point),
		status: readonly(status),
		start,
		stop,
		setPace,
		getPace,
		setRate,
		getRate,
		setDuration,
		getDuration,
		setLoop,
		getLoop
	}
	
}

export default useTimeline;